import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:zrjz/comm/base/empty_controller.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/router/getx_router_observer.dart';

import 'base_stateful_page.dart';
import 'global_key_factory.dart';

/*
 * 页面的基类，StatefulWidget 类型
 * 选择性使用，如果想要在 BaseStatefulPage 的 子State中使用 Controller 就可以用。
 * 如果没有传Key,则自动管理Key
 */
abstract class BaseState<T extends BaseStatefulPage<C>, C extends GetxController> extends State<T> {
  C? _controller;

  C get controller => _controller ?? EmptyController() as C;

  @override
  void initState() {
    _createController();
    super.initState();
  }

  @override
  void dispose() {
    Get.delete<C>(tag: widget.key?.toString());
    super.dispose();
  }

  void _createController() {
    try {
      _controller = GetInstance().find<C>(tag: widget.key?.toString());
    } catch (e) {
      _controller = null;
    }
  }

  //创建自动绑定Controller的GetBuilder
  GetBuilder<C> autoCtlGetBuilder({
    required Widget Function(C controller) builder,
    final Object? id, //Controller根据id来刷新指定的GetBuilder区域
    final bool autoRemove = true,
    final bool global = true,
    final bool assignId = false,
    final void Function(GetBuilderState<C> state)? initState,
    final void Function(GetBuilderState<C> state)? dispose,
    final void Function(GetBuilderState<C> state)? didChangeDependencies,
  }) {
    assert(_controller != null, "controller不能为空，请在 BaseState 与 BaseStatefulPage 中指定正确的泛型自动初始化");

    return GetBuilder<C>(
      init: _controller,
      tag: widget.key?.toString(),
      builder: builder,
    );
  }
}
